package com.hpf.redis7.mylock;

import cn.hutool.core.util.IdUtil;
import jakarta.annotation.Resource;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;

@Component
@NoArgsConstructor
public class DistributedLockFactory {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 防止机器意外挂了，重启后上一个线程被抢不到锁，因此每次重启自动在spring容器中生成一个新的uuid
     */
    private final String uuid = IdUtil.simpleUUID();

    public Lock getDistributedLock(LockType lockType) {
        return this.getDistributedLock(lockType, lockType.name().toLowerCase() + "DistributedLock");
    }

    public Lock getDistributedLock(LockType lockType, String lockName) {
        return switch (lockType) {
            case REDIS ->
                    new RedisDistributedLock(stringRedisTemplate, lockName, uuid + ":" + Thread.currentThread().getId());
            case ZOOKEEPER -> //TODO zookeeper版本的分布式锁
                    null;
            case MYSQL -> {
                //TODO MYSQL版本的分布式锁
                yield null;
            }
        };
    }
}
